package com.haruhinav.interecptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.haruhinav.Utils.JWTUtils;
import com.sun.javafx.geom.transform.SingularMatrixException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        Map<String,Object> map = new HashMap<>();
        //获取请求头中的token
        String token = request.getHeader("token");
        try {
            JWTUtils.verify(token);
            return true;
        }catch (SignatureVerificationException e){
//            e.printStackTrace();
            map.put("code",-5);
            map.put("msg","无效签名");
        }catch (TokenExpiredException e){
//            e.printStackTrace();
            map.put("code",-4);
            map.put("msg","token已过期");
        }catch(AlgorithmMismatchException e){
//            e.printStackTrace();
            map.put("code",-3);
            map.put("msg","token算法不一致");
        }catch (NullPointerException e){
//            e.printStackTrace();
            map.put("code",-2);
            map.put("msg","无token");
        }
        catch(Exception e){
//            e.printStackTrace();
            map.put("code",-1);
            map.put("msg","无效token");
        }

//        响应json字符串给前端
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(json);
        return false;
    }
}
